import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../common/MMKVTags.dart';
import '../common/iconfont.dart';
import '../main.dart';
import '../mc_router.dart';
import '../net/api/login_api.dart';
import '../net/base/base_api.dart';
import '../value/font_size.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<StatefulWidget> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool isPasswdVisiable = false;
  bool isPhoneCorrect = true;
  bool isLoginBtnAble = false;

  final TapGestureRecognizer _tapProtocolGesRecognizer = TapGestureRecognizer();

  //定义一个controller
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _passwdController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _phoneController.text = prefs.getString(MMKVTags.PHONE_NUMBER) ?? "";
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: [
            // 注册
            Padding(
              padding: const EdgeInsets.only(top: 16, right: 16).r,
              child: Align(
                alignment: Alignment.topRight,
                child: GestureDetector(
                  onTap: _onTapRegister,
                  child: Text(
                    '注册',
                    style: TextStyle(
                        color: Colors.blue,
                        fontSize: FontSize.fontSizeBig,
                        decoration: TextDecoration.none,
                        fontWeight: FontWeight.normal),
                  ),
                ),
              ),
            ),
            // 标题
            Container(
              margin: const EdgeInsets.only(top: 30, left: 20, bottom: 30).r,
              alignment: Alignment.centerLeft,
              child: Text(
                '欢迎登录养鱼端',
                style: TextStyle(
                    color: Colors.black,
                    fontSize: FontSize.fontSizeTitle,
                    decoration: TextDecoration.none),
              ),
            ),
            // 电话号码输入框
            Container(
              margin:
                  const EdgeInsets.only(top: 30, left: 20, bottom: 0, right: 20)
                      .r,
              height: 48.h,
              decoration: BoxDecoration(
                border: Border(
                    bottom:
                        BorderSide(width: 1.w, color: const Color(0xffe5e5e5))),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                    flex: 2,
                    child: Row(
                      children: [
                        Text(
                          '+86',
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: FontSize.fontSizeDefault,
                              fontWeight: FontWeight.normal,
                              decoration: TextDecoration.none),
                        ),
                        Icon(
                          IconFont.icon_arrow_right,
                          color: const Color(0xff222222),
                          size: FontSize.fontSizeDefault,
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                      flex: 8,
                      child: TextField(
                        style: TextStyle(fontSize: FontSize.fontSizeDefault),
                        enableInteractiveSelection: true,
                        keyboardType: TextInputType.phone,
                        decoration: const InputDecoration(
                            border: InputBorder.none, hintText: '请输入电话号码'),
                        onChanged: _onPhoneFieldChange,
                        controller: _phoneController,
                      )),
                ],
              ),
            ),
            // 手机号验证view
            if (!isPhoneCorrect)
              Container(
                margin: const EdgeInsets.only(left: 20, right: 20).r,
                child: Text(
                  '请输入正确的手机号码！',
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: FontSize.fontSizeSmall,
                    fontWeight: FontWeight.normal,
                    decoration: TextDecoration.none,
                  ),
                ),
              ),
            // 密码输入框
            Container(
              margin: const EdgeInsets.only(
                      top: 10, left: 20, bottom: 30, right: 20)
                  .r,
              height: 48.h,
              decoration: const BoxDecoration(
                border: Border(
                    bottom: BorderSide(width: 1, color: Color(0xffe5e5e5))),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                      flex: 9,
                      child: TextField(
                        style: TextStyle(fontSize: FontSize.fontSizeDefault),
                        obscureText: !isPasswdVisiable,
                        enableInteractiveSelection: true,
                        decoration: const InputDecoration(
                            border: InputBorder.none, hintText: '请输入密码'),
                        controller: _passwdController,
                        onChanged: _onPasswdFieldChange,
                      )),
                  Expanded(
                      flex: 1,
                      child: GestureDetector(
                        onTap: _onTapPasswdIcon,
                        child: Icon(
                          isPasswdVisiable
                              ? IconFont.icon_yanjing_zhengyan
                              : IconFont.icon_biyan,
                          size: FontSize.fontSizeBigX,
                          color: const Color(0xFFC5C5C5),
                        ),
                      )),
                ],
              ),
            ),
            // 登录按钮
            Container(
              margin: const EdgeInsets.only(left: 20, right: 20, top: 20).r,
              width: double.infinity,
              child: SizedBox(
                width: double.infinity,
                height: 48.w,
                child: ElevatedButton(
                  onPressed: isLoginBtnAble ? _onPressedLoginBtn : null,
                  style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all(const Color(0xff1566e2)),
                    shape: MaterialStateProperty.all(RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(24.w))),
                  ),
                  child: Text(
                    '登录',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: FontSize.fontSizeSmall,
                      fontWeight: FontWeight.normal,
                      decoration: TextDecoration.none,
                    ),
                  ),
                ),
              ),
            ),
            // 验证码登录 忘记密码
            Container(
              margin: const EdgeInsets.only(top: 30, left: 20, right: 20).r,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: _onTapCodeLogin,
                    child: Text(
                      '验证码登录',
                      style: TextStyle(
                          color: const Color(0xff969696),
                          fontSize: FontSize.fontSizeSmallX),
                    ),
                  ),
                  GestureDetector(
                    onTap: _onTapForgetPasswd,
                    child: Text(
                      '忘记密码',
                      style: TextStyle(
                          color: const Color(0xff969696),
                          fontSize: FontSize.fontSizeSmallX),
                    ),
                  ),
                ],
              ),
            ),
            // 协议
            const Spacer(
              flex: 1,
            ),
            GestureDetector(
              onTap: _onTapWechatLogin,
              child: Center(
                child: Image(
                    image: const AssetImage('assets/images/wechat_logo.png'),
                    width: 56.w,
                    height: 56.h),
              ),
            ),
            SizedBox(height: 8.h),
            Center(
              child: Text.rich(TextSpan(
                  style: TextStyle(fontSize: FontSize.fontSizeSmallX),
                  children: [
                    const TextSpan(text: '登录代表你已同意'),
                    TextSpan(
                        text: '校内用户协议、隐私政策',
                        style: const TextStyle(color: Colors.blue),
                        recognizer: _tapProtocolGesRecognizer
                          ..onTap = _onTapProtocol),
                  ])),
            )
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    //用到GestureRecognizer的话一定要调用其dispose方法释放资源
    _tapProtocolGesRecognizer.dispose();
    super.dispose();
  }

  //***************  下面为私有方法 *****************
  void _onTapRegister() {
    print(MCRouter.registerPage);
    Get.toNamed(MCRouter.registerPage);
    // Get.toNamed(MCRouter.appHomePage);
  }

  void _onTapPasswdIcon() {
    setState(() {
      isPasswdVisiable = !isPasswdVisiable;
    });
  }

  void _onPhoneFieldChange(String value) {
    const String regexPhoneNumber =
        "^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$";
    final RegExp reg = RegExp(regexPhoneNumber);
    setState(() {
      isPhoneCorrect = reg.hasMatch(value);
      isLoginBtnAble = (_phoneController.text.isNotEmpty &&
          isPhoneCorrect &&
          _passwdController.text.isNotEmpty);
    });
  }

  void _onPasswdFieldChange(String value) {
    setState(() {
      isLoginBtnAble = (_phoneController.text.isNotEmpty &&
          isPhoneCorrect &&
          _passwdController.text.isNotEmpty);
    });
  }

  void _onPressedLoginBtn() async {
    LoginApi api = LoginApi(LoginApi.LOGIN, RequestMethod.post);
    Map<String, dynamic> body = {
      "username": _phoneController.text,
      "password": _passwdController.text
    };

    // 存储手机号
    await prefs.setString(MMKVTags.PHONE_NUMBER, _phoneController.text);

    // var result = await api.requestAsync(body: body);
    // print("登录信息");
    // print(result);

    // LoginEntity loginEntity = LoginEntity.fromJson(result);

    // 将整个对象转为jsonStr存储
    // String loginEntityJsonStr = json.encode(loginEntity.toJson());
    // await prefs.setString(MMKVTags.LOGIN_INFO, loginEntityJsonStr);
    // await prefs.setString(MMKVTags.SCHOOL_CUR_ID, loginEntity.schoolId);

    // 将jsonStr取出并转为对象
    // String? decodeStr = prefs.getString("loginEntity");
    // if (decodeStr != null) {
    //   Map<String, dynamic> map = json.decode(decodeStr);
    //   LoginEntity loginEntity1 = LoginEntity.fromJson(map);
    // }

    /*print("请求具体实体：$loginEntity");
    print("属性实力：${loginEntity.token}");

    if (prefs.getString(MMKVTags.STUDENT_CUR_ID)==null && prefs.getString(MMKVTags.STUDENT_CUR_ID)!.isEmpty) {
      if (loginEntity.schools.isNotEmpty) {
        // 默认第一个
        await prefs.setString(MMKVTags.STUDENT_CUR_ID, loginEntity.schools[0].studentId);
        await prefs.setString(MMKVTags.CURRENT_SCHOOL, loginEntity.schools[0].id);
      }
    }
    // 存储数据到mmkv
    await prefs.setString(MMKVTags.TOKEN, loginEntity.token);
    await prefs.setString(MMKVTags.USERID, loginEntity.username);
    await prefs.setInt(MMKVTags.LAST_REFRESH_TOKEN_TIME, Global.currentTimeMills());
    await prefs.setBool(MMKVTags.LOGIN_TAG, true);*/

    await prefs.setBool(MMKVTags.LOGIN_TAG, true);
    // 跳转界面
    Get.toNamed(MCRouter.appHomePage);
  }

  void _onTapCodeLogin() {
    print('点击验证码登录');
    // Get.toNamed(MCRouter.verifyCodePage);
  }

  void _onTapForgetPasswd() {
    print('点击忘记密码');
  }

  void _onTapProtocol() {
    print('点击用户协议');
  }

  void _onTapWechatLogin() {
    print('点击微信登录！');
  }
}
